package cn.iocoder.yudao.module.promotion.coupon.api;

import cn.iocoder.yudao.framework.common.exception.Assertions;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.api.promotion.coupon.CouponTemplateApi;
import cn.iocoder.yudao.module.api.promotion.coupon.dto.CouponTemplateRespDTO;
import cn.iocoder.yudao.module.promotion.coupon.dal.dataobject.CouponTemplateDO;
import cn.iocoder.yudao.module.promotion.coupon.service.CouponTemplateService;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.*;

/**
 * 优惠劵模板 API 实现类
 *
 * @author 山野羡民
 */
@Service
@Validated
public class CouponTemplateApiImpl implements CouponTemplateApi {

    @Resource
    private CouponTemplateService couponTemplateService;

    @Nonnull
    @Override
    public List<CouponTemplateRespDTO> getCanTakeCouponTemplateListByShopId(Long shopId) {
        List<CouponTemplateDO> list = couponTemplateService.getCanTakeCouponTemplateListByShopId(shopId);
        return BeanUtils.toBean(list, CouponTemplateRespDTO.class);
    }

    @Nonnull
    @Override
    public Map<Long, List<CouponTemplateRespDTO>> getCanTakeCouponTemplateMap(Set<Long> shopIds) {
        List<CouponTemplateDO> list = couponTemplateService.getCanTakeCouponTemplateListByShopIds(shopIds);
        List<CouponTemplateRespDTO> dtos = BeanUtils.toBean(list, CouponTemplateRespDTO.class);
        Map<Long, List<CouponTemplateRespDTO>> map = new HashMap<>();
        for (CouponTemplateRespDTO dto : dtos) {
            map.computeIfAbsent(dto.getShopId(), key -> new ArrayList<>()).add(dto);
        }
        return map;
    }

    @Override
    public CouponTemplateRespDTO validateTemplate(Long id) {
        CouponTemplateDO entity = couponTemplateService.getCouponTemplate(id);
        Assertions.notNull(entity, "优惠劵模板不存在");
        return BeanUtils.toBean(entity, CouponTemplateRespDTO.class);
    }

}
